<template>
  <div class="task-list-container">
    <CPageTable @register="registerPage" v-model:search-form="searchForm">
      <template #headerRightButton>
        <el-button
          type="primary"
          @click="handleAddBomProduct"
          v-btnPermission="'PCF_PRODUCT_BOM_ADD'"
        >
          <CIcon class="g-mr4" type="c-xian-xinjian"></CIcon>
          新增
        </el-button>
      </template>
      <template #productName="{ scope }">
        <CTableColumn
          :main-text="scope.row.productName"
          :sub-text="scope.row.productModel"
        ></CTableColumn>
      </template>
      <template #enterprise="{ scope }">
        <CTableColumn
          :main-text="scope.row.enterpriseName"
          :sub-text="scope.row.enterpriseNo"
        ></CTableColumn>
      </template>
      <template #update="{ scope }">
        <CTableColumn
          :main-text="scope.row.updater"
          :sub-text="scope.row.dataModifyTime"
        ></CTableColumn>
      </template>
      <template #statusSlot="{ scope }">
        <el-tag :type="renderTag(scope.row.syncStatus)"
          >{{ SyncStatusMap[scope.row.syncStatus as keyof typeof SyncStatusEnum] }}
        </el-tag>
      </template>
      <template #partNum="{ scope }">
        <span v-if="!scope.row.partNum">{{ isNullOrUnDef(scope.row.partNum) ? '-' : 0 }}</span>
        <CLink
          v-else-if="hasBtnPermission('PCF_PRODUCT_BOM_VIEW') && scope.row.syncStatus == 'SYNCED'"
          @click="goDetail(scope.row)"
          >{{ scope.row.partNum }}</CLink
        >
        <span v-else>{{ scope.row.partNum }}</span>
      </template>

      <template #op="{ scope }">
        <CTableButtonGroup :showMoreNum="3" :buttons-config="getTableButtonsConfig(scope.row)" />
      </template>
    </CPageTable>
    <AddOrEditBomDialog
      v-model:visible="addOrEditBomProductVisible"
      :productNo="productNo"
      :type="addOrEditBomProductType"
      @refresh="refresh"
    ></AddOrEditBomDialog>
  </div>
</template>
<script lang="ts">
export default {
  name: 'Bom'
};
</script>
<script lang="ts" setup>
import { ref, reactive } from 'vue';
import AddOrEditBomDialog from './components/AddOrEditBomDialog/index.vue';
import { CPageTable, useCPageTable, CPageTableProps } from '@/components/CPageTable';
import { CTableColumn, CTableButtonGroup } from '@/components/CTable';
import type { TableButtonItem } from '@/components/CTable';
import { useBom } from './useBom';
import { useRouter } from 'vue-router';
import { useKeepAliveRefresh } from '@/hooks/useKeepAliveRefresh';
import { useMessage } from '@/hooks/useMessage';
import { delBomProduct, syncBomProduct } from '@/apis/system/config/bomProduct';
import { IBomProductListItem } from '@/apis/system/config/model/bomProductModel';
import { isNullOrUnDef } from '@/utils/is';
import { CLink } from '@/components/CLink/index';
import { useDebounceFn } from '@vueuse/core';
import { hasBtnPermission } from '@/directives/btnPermission';
import { SyncStatusEnum, SyncStatusMap } from '@/constants/pcf/index';

const { createMessage, createConfirm } = useMessage();
const { searchForm, searchOptions, tableOptions, tableFieldsSetting } = useBom();
const options = reactive<CPageTableProps>({
  title: '乘用车BOM',
  searchOptions: searchOptions,
  tableOptions,
  tableFieldsSetting,
  enableFieldsSetting: true
});
const router = useRouter();
const [registerPage, { refresh }] = useCPageTable(options);
useKeepAliveRefresh(refresh);

const productNo = ref('');
const addOrEditBomProductType = ref<'ADD' | 'EDIT'>('ADD');
const addOrEditBomProductVisible = ref(false);

// 新建任务
function handleAddBomProduct() {
  productNo.value = '';
  addOrEditBomProductType.value = 'ADD';
  addOrEditBomProductVisible.value = true;
}

// 编辑任务
function handleEditBomProduct(row: IBomProductListItem) {
  productNo.value = row.productNo;
  addOrEditBomProductType.value = 'EDIT';
  addOrEditBomProductVisible.value = true;
}
const goDetail = (row: IBomProductListItem) => {
  router.push(
    `/system/bom/productBomCollect/productItem?productNo=${row.productNo}&title=${row.productName}`
  );
};
/**
 * 删除供应商
 */

const handleDel = (row: IBomProductListItem) => {
  createConfirm('提示', '确认删除该车型？', {
    iconType: 'warning',
    confirmButtonText: '删除'
  }).then(() => {
    delBomProduct(row.productNo).then(() => {
      createMessage.success('删除成功！');
      refresh();
    });
  });
};

const handleFetchBom = async (row: IBomProductListItem) => {
  // isClicked 防止重复点击
  row.loading = true;
  try {
    row.syncStatus = SyncStatusEnum.SYNCING;
    await syncBomProduct(row.productNo);
    createMessage.success(`同步${row.productName}数据成功！`);
    refresh();
  } catch (err: any) {
    if (err?.data?.code === 420802) {
      refresh();
    }
  } finally {
    row.loading = false;
    console.log('error');
  }
};
const checkBom = (row: IBomProductListItem) => {
  if (row.partNum) {
    createConfirm('提示', '同步BOM数据会覆盖历史数据，请确认是否继续同步？', {
      iconType: 'warning',
      confirmButtonText: '确认'
    }).then(() => {
      handleFetchBom(row);
    });
  } else {
    handleFetchBom(row);
  }
};
const handlerThrottle = useDebounceFn(checkBom, 300);
/**
 * 配置表格的按钮
 * @param row 表格行数据
 */
function getTableButtonsConfig(row: IBomProductListItem): TableButtonItem[] {
  return [
    {
      text: '同步BOM数据',
      btnPermission: 'PCF_PRODUCT_BOM_SYNC',
      loading: row.loading,
      onClick: () => handlerThrottle(row)
    },
    // {
    //   text: '导入BOM数据',
    //   //   btnPermission: 'FACTOR_DETAIL',
    //   onClick: () => handleImport(row)
    // },
    {
      text: '编辑',
      btnPermission: 'PCF_PRODUCT_BOM_EDIT',
      onClick: () => handleEditBomProduct(row)
    },
    {
      text: '删除',
      btnPermission: 'PCF_PRODUCT_BOM_DELETE',
      onClick: () => handleDel(row)
    }
  ];
}

const renderTag = (status: keyof typeof SyncStatusEnum) => {
  switch (status) {
    case SyncStatusEnum.SYNCED:
      return 'success';
    case SyncStatusEnum.SYNCING:
      return '';
    case SyncStatusEnum.NOT_SYNCED:
      return 'info';
    default:
      return '';
  }
};
</script>
